package nciae.db.utils;


import nciae.db.pojo.dto.ApiDeleteCourseFileDTO;
import nciae.db.pojo.dto.ApiDeleteDiaryFileDTO;
import nciae.db.pojo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import nciae.db.common.CommonResult;
import nciae.db.pojo.dto.ApiDeleteFileDTO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;

import org.springframework.stereotype.Component;



@Component
public class FileUploadUtils {

    private static DocumentConverterUtils documentConverterUtils;

    @Autowired
    public void setDocumentConverterUtils(DocumentConverterUtils utils) {
        documentConverterUtils = utils;
    }

    public static final String FILE_PATH = "D:\\npt\\npt\\src\\main\\resources\\upload\\";
    public static final String FILE_URL = "http://192.168.240.182:8001/upload/";

    public static CommonResult<String> deleteHomeWorkFile(ApiDeleteFileDTO apiDeleteFileDTO) {

        CommonResult<String> result = new CommonResult<>();

        Long homeworkId = apiDeleteFileDTO.getHomeworkId();
        Long studentId = apiDeleteFileDTO.getStudentId();
        String fileName = apiDeleteFileDTO.getFileName();
        //对文件名做处理
        fileName = fileName.substring(fileName.lastIndexOf("/")+1);


        if(homeworkId == null || studentId == null || fileName == null){
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
            return result;
        }

        // 定义父目录
        String parentDirectory = "homeWorkFiles";
        // 根据学生 ID 和作业 ID 创建子目录
        String directoryImagePath = "";
        //判断文件是不是图片类型
        if(fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif")){
            directoryImagePath = FILE_PATH+ parentDirectory + File.separator + studentId + File.separator + homeworkId + File.separator + "img";
        }else{
            directoryImagePath = FILE_PATH + parentDirectory + File.separator + studentId + File.separator + homeworkId + File.separator + "file";
        }

        //在img文件夹下删除
        File file = new File(directoryImagePath, fileName);
        if (file.exists()) {
            if (file.delete()) {
                result.setCode(0);
                result.setMsg("文件删除成功");
            }
            System.out.println(result);
        }else{
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
        }
        return result;
    }

    public static CommonResult<String> deleteDiaryFile(ApiDeleteDiaryFileDTO apiDeleteDiaryFileDTO) {

        CommonResult<String> result = new CommonResult<>();

        Long projectId = apiDeleteDiaryFileDTO.getProjectId();
        Long userId = apiDeleteDiaryFileDTO.getUserId();
        String fileName = apiDeleteDiaryFileDTO.getFileName();
        String date = apiDeleteDiaryFileDTO.getDate();
        System.out.println(fileName);
        //对文件名做处理
        fileName = fileName.substring(fileName.lastIndexOf("/")+1);

        if(projectId == null || userId == null){
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
            return result;
        }

        // 定义父目录
        String parentDirectory = "DiaryFiles";
        // 根据学生 ID 和作业 ID 创建子目录
        String directoryImagePath = "";
        //判断文件是不是图片类型
        if(fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".jpeg") || fileName.endsWith(".gif")){
            directoryImagePath = FILE_PATH + parentDirectory + File.separator + userId + File.separator + projectId + File.separator+date+File.separator+ "img";
        }else{
            directoryImagePath = FILE_PATH  + parentDirectory + File.separator + userId + File.separator + projectId + File.separator+date+File.separator + "file";
        }
        //根据文件名进行递归删除文件
        File file = new File(directoryImagePath, fileName);

        if (file.exists()) {
            if (file.delete()) {
                result.setCode(200);
                result.setMsg("文件删除成功");
            } else {
                result.setCode(500);
                result.setMsg("服务器出错，请稍后重试！");
            }
        }
        return result;
    }


    public static CommonResult<String> uploadHomeWorkFiles(MultipartFile file, Long studentId, Long homeWorkId) {

        CommonResult<String> result = new CommonResult<>();

        // 定义父目录
        String parentDirectory = "homeWorkFiles";
        String directoryPath = "";
        //如果上传的是图片
        if (Objects.requireNonNull(file.getContentType()).startsWith("image")) {
            directoryPath  = FILE_PATH + parentDirectory + File.separator + studentId + File.separator + homeWorkId + File.separator + "img";
        }else{
            directoryPath  = FILE_PATH + parentDirectory + File.separator + studentId + File.separator + homeWorkId + File.separator + "file";
        }


        File directory = new File(directoryPath);

        // 检查目录是否存在，如果不存在则创建
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                result.setCode(500);
                result.setMsg("服务器出错，请稍后重试！");
                return result;
            }
        }

        // 获取文件名
        //利用 UUID 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + "_" + originalFilename;


        // 如果文件 originalFilename 已经存在，无法上传
        Path filePath = Paths.get(directoryPath, originalFilename);
        File targetFile = filePath.toFile();
        if (targetFile.exists()) {
            result.setCode(500);
            result.setMsg("存在已上传文件，请删除后重新上传");
            return result;
        }

        // 构建文件保存的完整路径
        filePath = Paths.get(directoryPath, fileName);
        System.out.println(fileName);

        try {
            // 将文件保存到指定路径
            Files.write(filePath, file.getBytes());
            result.setCode(200);
            result.setMsg("上传成功");
            result.setData(directoryPath + File.separator + fileName); // 返回文件的路径和名称
//            result.setData(fileName);
        } catch (IOException e) {
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
        }


        return result;

    }

    public static CommonResult<String> uploadDiaryFiles(MultipartFile file, Long userId, Long projectId,String date) {

        CommonResult<String> result = new CommonResult<>();
        System.out.println(date);
        System.out.println("oooooooooooooooooooooooooooooo");
        System.out.println("-----------------------------------------");

        // 定义父目录
        String parentDirectory = "DiaryFiles";
        String directoryPath = "";
        //如果上传的是图片
        if (Objects.requireNonNull(file.getContentType()).startsWith("image")) {
            directoryPath  = FILE_PATH + File.separator + userId + File.separator + projectId +File.separator + date + File.separator + "img";
        }else{
            directoryPath  = FILE_PATH  + File.separator + userId + File.separator + projectId + File.separator + date + File.separator + "file";
        }


        File directory = new File(directoryPath);

        // 检查目录是否存在，如果不存在则创建
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                result.setCode(500);
                result.setMsg("服务器出错，请稍后重试！");
                return result;
            }
        }

        // 获取文件名
        //利用 UUID 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + "_" + originalFilename;


        // 如果文件 originalFilename 已经存在，无法上传
        Path filePath = Paths.get(directoryPath, originalFilename);
        File targetFile = filePath.toFile();
        if (targetFile.exists()) {
            result.setCode(500);
            result.setMsg("存在已上传文件，请删除后重新上传");
            return result;
        }

        // 构建文件保存的完整路径
        filePath = Paths.get(directoryPath,fileName);

        try {
            // 将文件保存到指定路径
            Files.write(filePath, file.getBytes());
            result.setCode(200);
            result.setMsg("上传成功");
            result.setData(directoryPath + File.separator + fileName); // 返回文件的路径和名称
//            result.setData(directoryPath);
        } catch (IOException e) {
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
        }


        return result;

    }

    public static ResponseEntity<Resource> downloadAllFiles(String urlFile, String s) {
        return null;
    }


    //后台资料上传课件相关=》上传多个同时上传，时若是ppt  pdf  world 转为图片
    public static CommonResult<String> uploadCourseFiles(MultipartFile file, Integer courseId) {
        CommonResult<String> result = new CommonResult<>();
        // 定义父目录
        String parentDirectory = "CourseFiles";
        String directoryPath;
        directoryPath = FILE_PATH + parentDirectory + File.separator + courseId+ File.separator + "file";

        File directory = new File(directoryPath);
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                result.setCode(500);
                result.setMsg("服务器出错，请稍后重试！");
                return result;
            }
        }

        // 获取文件名
        //利用 courseId 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID() + "_" + originalFilename;

        Path filePath = Paths.get(directoryPath,fileName);
        try {
            // 将文件保存到指定路径
            Files.write(filePath, file.getBytes());
            result.setCode(0);
            result.setMsg("上传成功");
            directoryPath =directoryPath+ File.separator + fileName;
            result.setData(directoryPath);
        } catch (IOException e) {
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
        }
        return result;
    }
    //删除课程信息
    public static  CommonResult<String> deleteCourse(Integer id) {
        CommonResult<String> result = new CommonResult<>();
        if(id == null){
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
            return result;
        }
        // 定义父目录
        String parentDirectory = "CourseFiles";
        String directoryFilePath = FILE_PATH + parentDirectory + File.separator + id;
        boolean bol = deleteDirectory(new File(directoryFilePath));
        if(bol){
            result.setCode(0);
            result.setMsg("删除成功");
        }else{
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
        }
        return result;
    }

    public static CommonResult<String> deleteCourseFile(ApiDeleteCourseFileDTO apiDeleteCourseFileDTO) {

        CommonResult<String> result = new CommonResult<>();
        Integer CourseId = apiDeleteCourseFileDTO.getCourseId();
        String fileName = apiDeleteCourseFileDTO.getFileName();
        System.out.println(fileName);
        String url_image = apiDeleteCourseFileDTO.getUrl_image();
        System.out.println(url_image);

        if(CourseId == null || fileName == null){
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
            return result;
        }
        // 定义父目录
        String parentDirectory = "CourseFiles";
        // 根据CourseId 创建子目录
        String directoryFilePath = FILE_PATH + parentDirectory + File.separator + CourseId + File.separator+ "file"+File.separator+fileName;
        System.out.println(directoryFilePath);
        boolean bol = deleteDirectory(new File(directoryFilePath));
        boolean bol2;
        if(url_image!=null)
        {
            String uuid =fileName.split("_", 2)[0];
            String directoryImagePath = url_image+File.separator+uuid;
            bol2 = deleteDirectory(new File(directoryImagePath));
        }else {
            bol2 = true;
        }

        if (bol&&bol2){
            result.setCode(200);
            result.setMsg("文件删除成功");
            System.out.println("文件删除成功");
        }else{
            result.setCode(500);
            result.setMsg("服务器出错，请稍后重试！");
            System.out.println("文件删除失败");
        }
        return result;
    }


    public static boolean deleteDirectory(File directory) {
        // 如果路径不存在，直接返回true表示成功
        if (!directory.exists()) {
            return true;
        }
        System.out.println("sssssssss");
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    // 递归删除子文件或子目录
                    deleteDirectory(file);
                }
            }
        }
        // 删除空目录或文件
        return directory.delete();
    }


    /**
     * 根据Student对象删除该学生的所有作业文件和日志文件
     * @param student
     * @return
     */
    public static CommonResult<String> deleteStudentAllFiles(Student student) {
        CommonResult<String> result = new CommonResult<>();
        String homeworkFilePath = FILE_PATH + File.separator + "homeWorkFiles" + File.separator + student.getId() + File.separator;
        String diaryFilePath = FILE_PATH + File.separator + "DiaryFiles" + File.separator + student.getId() + File.separator;

        // 删除作业文件目录
        boolean homeworkDeleted = deleteDirectory(new File(homeworkFilePath));
        // 删除日志文件目录
        boolean diaryDeleted = deleteDirectory(new File(diaryFilePath));

        // 如果两个目录都不存在或者删除成功，返回成功
        if ((!new File(homeworkFilePath).exists() || homeworkDeleted) &&
                (!new File(diaryFilePath).exists() || diaryDeleted)) {
            result.setCode(200);
            result.setMsg("文件删除成功");
            System.out.println("文件删除成功");
        } else {
            result.setCode(500);
            result.setMsg("删除文件时出错，请稍后重试！");
            System.out.println("文件删除失败");
        }

        return result;
    }

    public static CommonResult<String>convertToImages(String path, Integer courseId,String uuid) {
        CommonResult<String> result = new CommonResult<>();
        String outputDir= FileUploadUtils.FILE_PATH + "CourseFiles" + File.separator + courseId + File.separator+ "img" + File.separator +uuid+File.separator;
        try {
            documentConverterUtils.convertDocumentToImages(path,outputDir);
            result.setCode(0);
            result.setMsg("转换成功");
        }catch (Exception e) {
            result.setCode(-1);
            result.setMsg("转换失败: " + e.getMessage());

        }
        return result;

    }

//    //将ppt转为图片序列
//    private static CommonResult<String> pptToImage(String pptFilePath,Integer id,String uuid) throws IOException {
//        String outputDir= FileUploadUtils.FILE_PATH + "CourseFiles" + File.separator + id + File.separator+ "img" + File.separator +uuid+File.separator;
//        CommonResult<String> result = new CommonResult<>();
//        // 创建目录
//        File dir = new File(outputDir);
//        if (!dir.exists() && !dir.mkdirs()) {
//            throw new IOException("无法创建目录: " + outputDir);
//        }
//        try(FileInputStream fis = new FileInputStream(pptFilePath);
//            XMLSlideShow ppt = new XMLSlideShow(fis);
//        ) {
//            Dimension pgsize = ppt.getPageSize();
//            int slideNumber = 0;
//            for (Slide slide : ppt.getSlides()) {
//                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
//                Graphics2D graphics = img.createGraphics();
//                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//                graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
//                graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
//                graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
//                graphics.setColor(Color.white);
//                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
//                slide.draw(graphics);
//                String imageName = id + slideNumber + ".png";
//                File outputFile = new File(outputDir + imageName);
//                ImageIO.write(img, "png", outputFile);
//                slideNumber++;
//            }
//            if (slideNumber > 0) {
//                result.setCode(0);
//                result.setMsg("转换成功");
//            }else {
//                result.setCode(400);
//                result.setMsg("转换失败");
//            }
//            return result;
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//
//    }
//
//
//
//    // pdf转为图片
//    private static CommonResult<String> pdfToImage(String pdfFilePath,Integer id,String uuid) throws IOException {
//        String outputDir= FileUploadUtils.FILE_PATH + "CourseFiles" + File.separator + id + File.separator+ "img" + File.separator +uuid+File.separator;
//        CommonResult<String> result = new CommonResult<>();
//        // 创建目录
//        File dir = new File(outputDir);
//        if (!dir.exists() && !dir.mkdirs()) {
//            throw new IOException("无法创建目录: " + outputDir);
//        }
//        PDDocument document = PDDocument.load(new File(pdfFilePath));
//        PDFRenderer renderer = new PDFRenderer(document);
//        int pageCount = document.getNumberOfPages();
//        int num=0;
//        for (int page = 0; page < pageCount; page++) {
//            BufferedImage image = renderer.renderImageWithDPI(page, 300, ImageType.RGB);
//            String imageName = id + page + ".png";
//            File outputFile = new File(outputDir + imageName);
//            ImageIO.write(image, "png", outputFile);
//            System.out.println(imageName);
//            num++;
//        }
//        document.close();
//        if (num>0)
//        {
//            result.setCode(0);
//            result.setMsg("转换成功");
//        }else {
//            result.setCode(400);
//            result.setMsg("转换失败");
//        }
//        return result;
//
//
//    }
//
//
//
//    // 将world转pdf
//    private static String worldToPdf(String worldFilePath, Integer id) throws Exception {
//        String outputDir = FileUploadUtils.FILE_PATH + "CourseFiles" + File.separator+ id + File.separator;
//        File dir = new File(outputDir);
//        System.out.println(outputDir);
//        if (!dir.exists() && !dir.mkdirs()) {
//            throw new IOException("无法创建目录: " + outputDir);
//        }
//        String pdfFilePath = outputDir + "temp_" + System.currentTimeMillis() + ".pdf";
//
//        // 加载Word文档
//        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(worldFilePath));
//        wordMLPackage.setFontMapper(new IdentityPlusMapper());
//
//        // 创建输出流
//        try (FileOutputStream out = new FileOutputStream(pdfFilePath)) {
//            // 使用Docx4j进行转换
//            Docx4J.toPDF(wordMLPackage, out);
//        }
//
//        return pdfFilePath;
//    }



}
